package zplh.com.commonlibrary.networker;


import android.annotation.SuppressLint;

import io.reactivex.Flowable;
import io.reactivex.FlowableTransformer;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;

/**
 * Created by yong hao zeng on 2018/6/30.
 */
public class NetWorker {
    private static NetWorker instance;
    private static Retrofit retrofit;
    public static void init(NetWorkerConfig config){

        retrofit = new Retrofit.Builder().baseUrl(config.baseUrl)
                .addConverterFactory(config.factory)
                .addCallAdapterFactory(config.rxJava2CallAdapterFactory)
                .build();


    }

    private NetWorker(){
    }

    public static NetWorker getInstance(){
        if (instance == null ){
            instance = new NetWorker();
        }
        return instance;
    }


    public  Retrofit getRetrofit() {
        if (retrofit == null)
            try {
                throw new Exception("请先初始化networker");
            } catch (Exception e) {
                e.printStackTrace();
            }
        return retrofit;
    }

    /**
     * 创建网络请求 回掉总是在主线程
     * @param observer retrofit 的接口
     * @param subscriber 回调
     */
    public void createNetAsync(Observable observer, NetCustomSubscriber subscriber){
        observer.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);

    }

    private  FlowableTransformer<ResponseBody, ResponseBody> ioMainDownload(){
        return (Flowable<ResponseBody> upstream) -> {
            return upstream.
                    map((ResponseBody responseBody) -> {
                        return responseBody;
                    });
        };
    }

    @SuppressLint("CheckResult")
    public FileDownLoadSubscriber downLoad(FileDownLoadSubscriber subscriber, String url){


        ApiServices apiServices = retrofit.create(ApiServices.class);
        return apiServices.getFile(url)
                .compose(ioMainDownload())
                .subscribeWith(subscriber);
    }


    /**
     * 创建同步网络请求
     * @param observer retrofit 的接口
     * @param subscriber 回调
     */
    public void createNetSync(Observable observer, NetCustomSubscriber subscriber){
        observer.subscribe(subscriber);

    }


}
